import { Component, OnInit, Output, Input, EventEmitter } from '@angular/core';
const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) };
import { HttpClient, HttpParams, HttpHeaders } from '@angular/common/http';
import { Router } from '@angular/router';
import { NzModalRef, NzFormatEmitEvent, NzModalService, NzTreeComponent, NzTreeNodeOptions, NzMessageService } from 'ng-zorro-antd';
import { PagesService } from '../../services/pages.service';
import { UtilService } from '../../services/util.service';
import { RequestService } from '../../services/request.service';
declare var layui: any;
declare var layer: any;
declare var $: any;

@Component({
  selector: 'app-transfer',
  templateUrl: './transfer.component.html',
  styleUrls: ['./transfer.component.scss']
})
export class TransferComponent implements OnInit {

  constructor(public router: Router, private http: HttpClient, public interfaceService: PagesService, public utilService: UtilService, public request: RequestService) {

  }

  @Output() private outer = new EventEmitter();
  @Input() puc_msg: any;


  ngOnInit() {
    this.request.getProdCat1().subscribe((data) => {//商品树一级分类
      this.nodes = data;
      this.request.getBrand().subscribe((data) => {//品牌名称
        this.data1_sel['brandId'] = data.object.list;
        this.request.getColor().subscribe((data) => {//所有颜色
          this.colorName_list = data.object.list;
          this.request.getSpec().subscribe((data) => {//所有规格
            this.specId_list0 = data.object;
          });
        });
      });
    })
    this.data1_sel['prodStatus'] = JSON.parse(localStorage.getItem('prodStatus_list'))	//商品状态
  }

  nodes = [];
  brandId = [];
  colorName_list = [];
  specId_list0 = [];
  data1_sel = []
  ddata = [];
  tree2(e: Required<NzFormatEmitEvent>): void {
    if (e.node.getChildren().length === 0 && e.node.isExpanded) {
      if (e.node.origin.key) {
        this.loadNode('/erp/product/prodCat/opetion?prodCatId=' + e.node.origin.key).then((data: any) => {
          e.node.addChildren(data.object.list);
        });
      } else {
        e.node.addChildren(this.ddata);
      }
    }
  }

  xiaNodws = [];
  loadNode(xia): Promise<any[]> {
    this.interfaceService.getPages(xia, 1, 1000).subscribe((data: any) => {
      if (this.interfaceService.codeValidation(data)) {
        this.xiaNodws = data;
      }
    });
    return new Promise(resolve => {
      setTimeout(() => resolve(this.xiaNodws),
        1000);
    });
  }

  //商品选择

  popup01_url = '';
  popup01_para
  popup01_fieldParam = []
  popup01_fieldParam2 = []
  popup01_data1 = []
  popup01_docType = null
  popup01_json = {}
  popup01_brush
  popup01 = false;
  field01 = []     //table表格1-主表列字段集合
  data01 = {}      //table表格1-主表对象数据集合
  /**
   * docType  单据类型
   * json 提交时拼接参数
   * @param para url参数
   * @param fieldParam 单据明细传参对象对应主表基准字段
   * @param fieldParam2 单据明细商品数组对应明细基准字段
   * @param data1 原主表数据对象集合
   * @brush brush 是否刷选，默认不刷选（不传值），传值1为查询时刷选左侧值（且左侧值不清空）
   * @param url 可选，传参为替换url
   */
  popup01_show(docType, json, para, fieldParam, data1, switchUnitId, brush?, url?): void {
    this.popup01_docType = docType
    this.popup01_json = json
    this.popup01_brush = brush
    this.popup01_url = url
    this.popup01_fieldParam = fieldParam
    this.popup01_data1 = data1
    if (typeof (url) === 'undefined') {
      this.popup01_url = '/erp/purchase/unitProdCls/billProdlist?1=1' + para
    } else {
      this.popup01_url = url + '?1=1' + para
    }
    this.interfaceService.postPage('/erp/common/fields/getfieldsbytype', { 'type': 'purchase.DtlProdVo' }).subscribe((data: any) => {
      if (this.interfaceService.codeValidation(data)) {
        if (data.code == 200) {
          this.field01 = this.utilService.filed_list4(data.object, 1);
          this.popup01_fieldParam2 = this.interfaceService.fieldProdParam(data.object);
          this.popup01 = true;
          this.popup01_table();
          for (var i = 0; i < data.object.length; i++) {
            this.data01[data.object[i]['fieldValue']] = ''
          }
        }
      }
    });
    this.interfaceService.postPage("/erp/product/getOption/rhBrand", { switchUnitId: switchUnitId }).subscribe((data: any) => {
      if (this.interfaceService.codeValidation(data)) {
        if (data.code == 200) {
          this.data1_sel['brandId'] = data.object['brandId']
        }
      }
    });
  }

  popup01_hide(): void {
    this.popup01 = false;
    this.popup01_url = '';
    for (let i in this.searchData) {
      this.searchData[i] = ''
    }
    this.data0 = [];
    this.data1 = [];
    this.data2 = [];
    this.data3 = [];
    this.indexFlag=false;
  }
  searchData = {
    prodCode: '',
    prodName: '',
    prodCatId: '',
    inputCode: '',
    brandId: '',
    prodStatus: ''
  }
  maxNum = 20;
  data0: any = [];//初始所有数据
  data1: any = [];//初始化已选数据,赋值左框
  data2: any = [];//初始化剩余数据，赋值右框
  data3: any = [];//初始化已选左框固定数据，不绑定，防止数据更改
  indexFlag=false;
  popup01_table(i?) {
    if (this.popup01_brush === 1) {
      if(this.indexFlag){
        layui.use(['table', 'form', 'transfer2'], () => {
          var  transfer2 = layui.transfer2, form = layui.table;
          this.data1 = transfer2.get(this.tb1, 'l');
        });
      }
    }else{
      this.data1 = [];
    }
    this.data2 = [];
    this.indexFlag=true;
    var url = this.popup01_url + '&prodCode=' + this.searchData['prodCode'] + '&prodName=' + this.searchData['prodName'] + '&prodCatId='
      + this.searchData['prodCatId'] + '&inputCode=' + this.searchData['inputCode'] + '&brandId=' + this.searchData['brandId'] + '&prodStatus=' + this.searchData['prodStatus'];
    this.interfaceService.getPages(url, 1, this.maxNum).subscribe((data: any) => {
      if (this.interfaceService.codeValidation(data)) {
        if (data.code == 200) {
          const datas = data.object.list;
          for (var i = 0; i < datas.length; i++) {//筛选右框值
            var flag = true;
            for (var x = 0; x < this.data1.length; x++) {
              // console.log(i,datas[i],this.data1[x],'11111',this.utilService.isObjEqual(datas[i],this.data1[x]),this.utilService.isObjEqual({id:1,name:"张三"},{id:1,name:"张三"}))
              if (this.utilService.isObjEqual(datas[i],this.data1[x])) {
                flag = false;
                break;
              }
            }
            if (this.popup01_brush === 1) {
              if (flag) {
                this.data2.push(datas[i]);
              }
            } else {
              this.data2.push(datas[i]);
            }
          }
          this.popup01_listTable();
        } else {
          layer.msg(data.message);
        }
      }
    });
  }

  tb1
  popup01_listTable(): void {
    setTimeout(() => {
      layui.use(['table', 'form', 'transfer2'], () => {
        var  transfer2 = layui.transfer2, form = layui.table;
        var data1 = this.data1;
        var data2 = this.data2;
        var cols = this.field01;
        var tabConfig = { 'page': false, 'limit': 5000, 'height': 400, cellMinWidth: 120 }
        this.tb1 = transfer2.render({
          elem: '#popup01_root', //指定元素
          cols: cols, //表格列  支持layui数据表格所有配置
          data: [data1, data2], //[左表数据,右表数据[非必填]]
          tabConfig: tabConfig //表格配置项 支持layui数据表格所有配置
        })
      });
    }, 50);

  }


  popup01_sub() {
    layui.use(['table', 'form', 'transfer2'], () => {
      var  transfer2 = layui.transfer2, form = layui.table;
      var datas: any = this.utilService.cskSave(this.data3, transfer2.get(this.tb1, 'l'));
      var data = this.interfaceService.postEdidFields(this.popup01_docType, this.popup01_json, this.popup01_fieldParam, this.popup01_fieldParam2, this.popup01_data1, datas.data1);
      this.popup01_hide();
      this.outer.emit(data)

    });
  }

}
